//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - S+S Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Shp.Runtime.Contract;
using LitwareHR.PublicApp.WinUX;
using System.Globalization;
using LitwareHR.Recruiting.Contract;
using LitwareHR.Infrastructure.Interface;
using Microsoft.Practices.CompositeUI;
using LitwareHR.PublicApp.WinUX.DSA;
using Microsoft.Practices.SmartClient.ConnectionMonitor;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI.EventBroker;
using LitwareHR.Infrastructure.Interface.Constants;

using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Collections.ObjectModel;
 
namespace LitwareHR.PublicApp.WinUX.Services
{
    public class RecruitingService
    {
        private DSA.Secure.ProcessService.Agent spsAgent = null;
        private DSA.Secure.DataModelService.Agent sdmAgent = null;
        private AuthenticationService authnService = null;
        private ConnectionMonitor connectionMonitor = null;
        private OfflineDataService offlineService = null;
        private int numberOfCandidates;

        private ProcessService processService = null;
        
        [InjectionConstructor] 
        public RecruitingService([ServiceDependency] AuthenticationService authnService,
                                 [ServiceDependency] DSA.Secure.ProcessService.Agent spsAgent,
                                 [ServiceDependency] DSA.Secure.DataModelService.Agent sdmAgent,   
                                 [ServiceDependency] ConnectionMonitor connectionMonitor,
                                 [ServiceDependency] OfflineDataService offlineService,
                                 [ServiceDependency] ProcessService processService
                                 )
        {
            this.spsAgent = spsAgent;
            this.sdmAgent = sdmAgent;
            this.connectionMonitor = connectionMonitor;
            this.offlineService = offlineService;
            this.processService = processService;
            this.authnService = authnService;
        }

        [EventPublication(EventTopicNames.DataSynchronized, PublicationScope.Global)]
        public event EventHandler<EventArgs> DataSyncronized;

        [EventPublication(EventTopicNames.DataSynchronizing, PublicationScope.Global)]
        public event EventHandler<EventArgs> DataSyncronizing;


        public void Initialize()
        {
            AddAgentEventHandlers();
            
        }
                
        private void AddAgentEventHandlers()
        {            
            DSA.Secure.DataModelService.Callback.AddInstanceReturn += new EventHandler<LitwareHR.PublicApp.WinUX.DSA.Secure.DataModelService.AddInstanceEventArgs>(Callback_AddInstanceReturn);
        }

        void Callback_AddInstanceReturn(object sender, LitwareHR.PublicApp.WinUX.DSA.Secure.DataModelService.AddInstanceEventArgs e)
        {
            Collection<Field> fields = new Collection<Field>();
            EntityField[] list = e.Parameters[1] as EntityField[];
            foreach (EntityField entityField in list)
            {                
                fields.Add(new Field(entityField.Name, entityField.Value));
            }
            LitwareHR.Recruiting.Contract.Position position = new LitwareHR.Recruiting.Contract.Position(e.Id, fields);
            ServiceProxy.Secure.ProcessService processService = new LitwareHR.PublicApp.WinUX.ServiceProxy.Secure.ProcessService();
            processService.OpenRecruitingProcess(position); 
        }              
                
        private bool Connected()
        {
            return connectionMonitor.IsConnected; 
        }
        
        private bool Changed(StringPair[] view, DataTable table)
        {
            if (view.Length + 1 != table.Columns.Count)
                return true;
            
            foreach (StringPair field in view)
            {
                if (table.Columns[field.Key] == null)
                    return true; 
            }

            return false;            
        }


        /// <summary>
        /// Synchronizes local data against those stored in LitwareHR
        /// </summary>
        public void SyncronizeData()
        {
            if (Connected())
            {
                Collection<Guid> positions = processService.GetOpenPositionList(authnService.CurrentTenant.Id);

                if (positions.Count > 0)
                {
                    if (offlineService.DeleteClosedPositions(Constants.Entity.Position, "id", positions) > 0)
                    {
                        OnDataSyncronizing(null);
                        OnDataSyncronized(null);
                    }
                }

                List<Guid> openPositions = offlineService.GetOpenPositionIds();

                for (int i = 0; i < positions.Count; i++)
                {
                    foreach (Guid existId in openPositions)
                    {
                        if (positions[i].Equals(existId))
                        {
                            positions.RemoveAt(i);
                            i--;
                            break;
                        }
                    }
                }

                while (positions.Count > 50)
                    positions.RemoveAt(0);

                StringPair[][] instanceList = processService.GetOpenPositions(authnService.CurrentTenant, positions);
                StringPair[][] candidateList = processService.GetRecruitingWorkflowList(true);
                bool syncronize = candidateList.Length != numberOfCandidates;
                numberOfCandidates = candidateList.Length;

                if (instanceList != null || syncronize)
                {
                    OnDataSyncronizing(null);
                    try
                    {
                        if (instanceList != null)
                            offlineService.UpdateEntityTable(Constants.Entity.Position, "id", instanceList);
                    }
                    catch (Exception ex)
                    {
                        bool rethrow = ExceptionPolicy.HandleException(ex, "Default Policy");
                        if (rethrow)
                        {
                            throw;
                        }
                    }
                    OnDataSyncronized(null);
                }
            }
        }
        
        
        public DataTable GetOpenPositionsDetails()
        {
            DataTable dt = offlineService.GetOpenPositions();
            
            return dt;
        }

        public Collection<Position> GetOpenPositionEntityList()
        {
            return processService.GetOpenPositionEntityList();
        }

        public string GetPositionName(Guid id)
        {
            return GetPositionName(GetOpenPositionEntityList(), id);
        }

        public string GetPositionName(Collection<Position> positions, Guid id)
        {
            string name = string.Empty;

            for (int i = 0; (i < positions.Count) && (name == string.Empty); i++)
            {
                if (positions[i].Id.Equals(id))
                {
                    string title = string.Empty;
                    string code = string.Empty;
                    for (int f = 0; (f < positions[i].Fields.Count); f++)
                    {
                        if (positions[i].Fields[f].Name.ToUpper().Equals("TITLE"))
                        {
                            title = positions[i].Fields[f].Value;
                        }
                        if (positions[i].Fields[f].Name.ToUpper().Equals("CODE"))
                        {
                            code = positions[i].Fields[f].Value;
                        }
                    }
                    name = string.Format("{0} ({1})", title, code);

                }
            }
            return name;
        }
        
        public DataTable GetRecruitingWorkFlowList()
        {
            DataTable table = null;

            if (Connected())
            {
                table = new DataTable();
                StringPair[][] list = processService.GetRecruitingWorkflowList(true);                                
                table.Locale = CultureInfo.InvariantCulture;
                TranslateListToDataTable(list, table);
                offlineService.UpdateEntityTable("RecruitingWorkFlowList", "WorkflowId", list); 
            }
            else
            {
                table = offlineService.GetRecruitingWorkFlowList();                
            }

            return table;
        }
       
        private void TranslateListToDataTable(StringPair[][] list, DataTable table)
        {
            if (list.Length > 0)
            {                
                foreach (StringPair field in list[0])
                {                   
                        table.Columns.Add(field.Key);
                }
                foreach (StringPair[] record in list)
                {
                    DataRow row = table.NewRow();
                    List<StringPair> workflow = new List<StringPair>(record);
                    foreach (StringPair field in workflow)
                    {
                            row[field.Key] = field.Value;
                    }
                    table.Rows.Add(row);
                }
            }
        }

        public Resume GetResume(Guid resumeId)
        {
            return processService.GetResume(resumeId);
        }
                
        public DataTable GetRecruitingWorkFlowListByApplicant()
        {
            DataTable table = null;

            if (Connected())
            {
                table = new DataTable();
                StringPair[][] list = processService.GetRecruitingWorkflowListByApplicant(true);
                table.Locale = CultureInfo.InvariantCulture;
                TranslateListToDataTable(list, table);                
            }
            else
            {
                table = offlineService.GetRecruitingWorkflowListByApplicant();                
            }

            return table;
        }
        
        public void SubmitResume(Resume resume)
        {
            spsAgent.SubmitResume(resume);             
        }

        public EntityField[] GetPositionFields()
        {
            return offlineService.GetEntityDef(Constants.Entity.Position);
        }

        public void OpenPosition(EntityField[] list)
        {
            sdmAgent.AddInstance(Constants.Entity.Position, list);
            
            //Update the local store
            if (!Connected())
            {
                offlineService.AddInstance(Constants.Entity.Position, list);
            }
        }

        protected virtual void OnDataSyncronizing(EventArgs eventArgs)
        {
            if (DataSyncronizing != null)
            {
                DataSyncronizing(this, eventArgs);
            }
        }

        protected virtual void OnDataSyncronized(EventArgs eventArgs)
        {
            if (DataSyncronized != null)
            {
                DataSyncronized(this, eventArgs);
            }
        }

        internal SilverlightAccount GetSilverlightAccount()
        {
            return processService.GetSilverligtAccount();
        }
    }
   
}
